
package com.cnvp.paladin.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;

import com.cnvp.paladin.core.BaseController;
import com.cnvp.paladin.core.MyCallback;
import com.cnvp.paladin.model.Equipment;
//import com.cnvp.paladin.model.Equipmentsample;
import com.cnvp.paladin.model.Panel;
import com.cnvp.paladin.model.Phymapping;
import com.cnvp.paladin.model.Room;
import com.cnvp.paladin.model.Scene;
import com.cnvp.paladin.model.Sceneconfig;
import com.cnvp.paladin.model.SysUser;
import com.cnvp.paladin.model.SysUserRole;
import com.cnvp.paladin.utils.beetl.fn.XssEncodeUtils;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class EquipmentController extends BaseController {

    boolean flag = false;

    /**
     * if the user is superadmin
     * 
     * @return return the userID
     */
    public int issuperadmin() {
        SysUser currentUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        int userID = currentUser.get("id");
        List<SysUserRole> sur = currentUser.getRoles();
        for (SysUserRole sr : sur) {
            if (sr.getInt("role_id") == 4)
                flag = true;
        }
        return userID;
    }

    /**
     * 
     * @param status_code
     *            describe the status_code such as 0,305,300
     * @param data
     * @param status
     * @return
     */
    public Map<String, Object> putjson(Object status_code, Object data, Object status) {
        Map<String, Object> json = new HashMap<String, Object>();
        json.put("code", status_code);
        json.put("data", data);
        json.put("msg", status);
        return json;

    }

    public String sql() {
        String findSql = "(1=1) and ";
        Equipment eq = getModel(Equipment.class, "equipment");
        String[] attrs = eq.getAttrNames();
        Object[] values = eq.getAttrValues();
        for (int i = 0; i < attrs.length; i++) {
            System.out.println(attrs[i] + values[i]);
            Object a = null;
            if (null != values[i]) {
                a = values[i].getClass();
                findSql += (attrs[i] + "=" + "\"" + values[i] + "\"" + " and ");
            }
        }
        return findSql;
    }

    /*
     * to fina all scene
     */
    public List<Scene> findscene() {
        List<Scene> a = Scene.dao.findAll();
        return a;

    }

    public void index() {
        setAttr("page", Equipment.dao.paginate(getParaToInt(0, 1), 10));
        int userID = issuperadmin();
        if (flag == true) {
            setAttr("page", Equipment.dao.paginate(getParaToInt(0, 1), 10));
        } else {
            String sql = "where user_id =" + userID;
            setAttr("page", Equipment.dao.paginate(getParaToInt(0, 1), 10, sql));
        }
    }

    public void find() {
        Map<String, Object> json = new HashMap<String, Object>();
        String room_name = getPara("room.name");
        if (isPost()) {
            int userID = issuperadmin();
            String findsql = sql();
            if (flag == true) {
                findsql += " (1=1);";
            } else {
                findsql += "user_id=" + userID + " and ";
                findsql += " (1=1);";
            }
            List<Equipment> data = Equipment.dao.where(findsql);
            if (data.size() != 0) {
                json = putjson("0", data, "success");
            } else {
                json = putjson("305", data, "返回数据为空");
            }

        }
        renderJson(json);
    }

    public void getlist() {
        Map<String, Object> json = new HashMap<String, Object>();
        int userID = issuperadmin();
        if (flag == true) {
            List<Equipment> data = Equipment.dao.where("");
            json = putjson("0", data, "success");

        } else {
            String findSql = "(1=1) and ";
            findSql += "user_id=" + userID + " and ";
            findSql += " (1=1);";
            List<Equipment> data = Equipment.dao.where(findSql);
            json = putjson("0", data, "success");
        }

        renderJson(json);
    }

    public void create() {
        String is_app = getPara("is_app");
        Equipment eq = getModel(Equipment.class, "equipment");
        int userID = issuperadmin();
        eq.set("user_id", userID);
        if (isPost()) {
            if (null == eq.get("name") || null == eq.get("logic_id") || null == eq.get("room_name")) {
                renderJson(putjson("301", "", "缺少參數"));
            } else {
                String findLogic_id = "logic_id =" + eq.get("logic_id") + " and user_id = " + userID;
                String findLogic_id1 = "equipment_id =" + eq.get("logic_id");
                List<Equipment> data = Equipment.dao.where(findLogic_id);
                // List<Sceneconfig> sceneconfig =
                // Sceneconfig.dao.where(findLogic_id1);
                if (data.size() != 0) {
                    Equipment a = data.get(0);
                    int id = a.get("id");
                    Equipment equ = getModel(Equipment.class, "equipment").set("id", id);
                    equ.update();
                    String sqlFind = "select * from cnvp_sceneconfig where equipment_logic_id =" + " "
                            + eq.get("logic_id") + " " +"and user_id = " + userID ;
                    List<Record> sceneconfig = Db.find(sqlFind);
                    for (int i = 0; i < sceneconfig.size(); i++)
                        Db.update("cnvp_sceneconfig", sceneconfig.get(i).set("room_name", eq.get("room_name")));
                    if ("1".equals(is_app)) {
                        renderJson(putjson("0", "", "设备已存在,所以把他从单品移除，天价到对应区域"));
                    } else {
                        redirect(getControllerKey());
                    }
                } else {
                    eq.set("user_id", userID).save();
                    String equipment_logic_id = (String) eq.getAttrs().get("logic_id");
                    int equipment_id = (Integer) eq.getAttrs().get("id");
                    // Object[] scene = findscene();
                    List<Scene> b = findscene();
                    int size = b.size();
                    for (int i = 0; i < 7; i++) {
                        Scene scene = b.get(i);
                        int scene_id = scene.getInt("id");
                        String scene_name = scene.get("name");
                        String image = scene.get("image_id");
                        int id_scene = i + equipment_id * 10;
                        String param1 = scene.get("param1");
                        String param2 = scene.get("param2");
                        String param3 = scene.get("param3");
                        String param4 = scene.get("param4");
                        String param5 = scene.get("param5");
                        Record sceneconfig1 = new Record().set("id", id_scene).set("user_id", userID)
                                .set("param1", param1).set("param2", param2).set("param3", param3).set("param4", param4)
                                .set("param5", param5).set("equipment_logic_id", equipment_logic_id)
                                .set("equipment_id", equipment_id).set("scene_id", scene_id).set("status", "0")
                                .set("scene_name", scene_name).set("image", image)
                                .set("room_name", eq.get("room_name")).set("tag", "0").set("type", eq.get("type"));
                        Db.save("cnvp_sceneconfig", sceneconfig1);
                    }
                    for(int i = 7; i<b.size(); i++){
                        Scene scene = b.get(i);
                        int scene_id = scene.getInt("id");
                        String scene_name = scene.get("name");
                        String image = scene.get("image_id");
                        int id_scene = i + equipment_id * 10;
                        String param1 = scene.get("param1");
                        String param2 = scene.get("param2");
                        String param3 = scene.get("param3");
                        String param4 = scene.get("param4");
                        String param5 = scene.get("param5");
                        Record sceneconfig1 = new Record().set("id", id_scene).set("user_id", userID)
                                .set("param1", param1).set("param2", param2).set("param3", param3).set("param4", param4)
                                .set("param5", param5).set("equipment_logic_id", equipment_logic_id)
                                .set("equipment_id", equipment_id).set("scene_id", scene_id).set("status", "0")
                                .set("scene_name", scene_name).set("image", image)
                                .set("room_name", eq.get("room_name")).set("tag", 1).set("type", eq.get("type"));
                        Db.save("cnvp_sceneconfig", sceneconfig1);
                    }
                    if ("1".equals(is_app)) {
                        renderJson(putjson("0", "", "success"));
                    } else {
                        redirect(getControllerKey());
                    }
                }
                return;
            }
        } else {
            Equipment data = new Equipment();
            setAttr("data", data);
            render("form.html");
        }
    }

    public void update() {
        String is_app = getPara("is_app");
        int userID = issuperadmin();
        if (isPost()) {
            String flag = getPara("equipment.logic_id");
            int id = 0;
            if (null == flag && null != getParaToInt()) {
                id = getParaToInt();
            } else if (!flag.isEmpty()) {
                String logic_id = getPara("equipment.logic_id");
                String findSql = "(1=1) and ";
                findSql += "logic_id =" + "\"" + logic_id + " and  user_id = "
                        + "\"" + userID + "\";";;
                findSql += " (1=1);";
                List<Equipment> data = Equipment.dao.where(findSql);
                Equipment a = data.get(0);
                id = a.get("id");
            }
            // 检查ID是否存在
            Equipment eqp = Equipment.dao.findById(id);
            if (null == eqp) {
                renderJson(putjson("307", "", "该主键不存在"));
            } else {
                // 检验是否非空字段全部填写
                Equipment eq = getModel(Equipment.class, "equipment").set("id", id);
                if (null == eq.get("name") || null == eq.get("logic_id") || null == eq.get("room_name")) {
                    renderJson(putjson("301", "", "缺少参数"));
                } else {
                    if (eq.update()) {
                        if ("1".equals(is_app)) {
                            renderJson(putjson("0", "", "修改设备成功"));
                        } else {
                            redirect(getControllerKey());
                        }
                        return;
                    }
                }
            }
        } else {
            setAttr("data", Equipment.dao.findById(getParaToInt()));
            render("form_update.html");
        }
    }

    public void delete() {
        String is_app = getPara("is_app");
        int userID = issuperadmin();
        String flag = getPara("equipment.logic_id");
        int id = 0;
        String logic_id = null;
        boolean f = false;
        if (flag == null) {
            f = true;
        }
        if (f && getPara() != null) {
            logic_id = getPara();
        } else if (getPara("equipment.logic_id") != null) {
            logic_id = getPara("equipment.logic_id");
        }
        String findSql = "logic_id =" + "\"" + logic_id + "\"" + " and  user_id = " + "\"" + userID + "\";";
        List<Equipment> data = Equipment.dao.where(findSql);
        if (data.size() != 0) {
            Equipment a = data.get(0);
            logic_id = a.get("logic_id");
            id = a.get("id");
            Equipment eq = Equipment.dao.findById(id);
            String DeleteSql = "DELETE FROM cnvp_sceneconfig WHERE equipment_logic_id =" + logic_id + " and  user_id = "
                    + "\"" + userID + "\";";
            MyCallback callbcack1 = new MyCallback(DeleteSql);
            Db.execute(callbcack1);
            eq.delete();

            if ("1".equals(is_app)) {
                renderJson(putjson("0", "", "删除设备成功"));
            } else {
                redirect(getControllerKey());
            }
        } else {
            renderJson(putjson("307", "", "该主键不存在"));
        }
    }

    public void deleteAll() {
        String is_app = getPara("is_app");
        Integer[] ids = null;
        if (!getPara("equipment.id").isEmpty()) {
            ids = getParaValuesToInt("equipment.id");
        } else {
            renderJson(putjson("307", "", "该主键不存在"));
            return;
        }
        boolean flag = true;
        for (Integer id : ids) {
            Equipment eq = Equipment.dao.findById(id);
            if (eq != null) {
                eq.delete();
            } else {
                flag = false;
            }
        }
        if ("1".equals(is_app) && flag == true) {
            renderJson(putjson("0", "", "批量删除设备成功"));
        } else if ("1".equals(is_app) && flag == false) {
            renderJson(putjson("307", "", "该主键不存在"));
        } else {
            redirect(getControllerKey());
        }
    }

    public void getRoom() {
        List<Room> roomname = Room.dao.findAll();
        List<Integer> row = new ArrayList<Integer>();
        Iterator<Room> it = roomname.iterator();
        while (it.hasNext()) {
            Room room = (Room) it.next();
            row.add((Integer) room.get("id"));
        }
        renderJavascript(JsonKit.toJson(row));
    }

    public void getPanel() {
        List<Panel> panelname = Panel.dao.findAll();
        List<String> row = new ArrayList<String>();
        Iterator<Panel> it = panelname.iterator();
        while (it.hasNext()) {
            Panel panel = (Panel) it.next();
            System.out.println(XssEncodeUtils.htmlEncode((String) panel.get("name")));
            row.add(XssEncodeUtils.htmlEncode((String) panel.get("name")));
        }
        renderJavascript(JsonKit.toJson(row));
    }

}
